#include <iostream>
#include <sys/types.h>
#include <string>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>

void Usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << "serverip serverport" << std::endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }

    uint16_t serverport = std::stoi(argv[2]);
    std::string serverip = argv[1];

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        exit(2);
    }

    struct sockaddr_in server;
    memset(&server, 0, sizeof(struct sockaddr_in));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    server.sin_port = htons(serverport);

    // 客户端不需要调用bind 函数

    // 客户端与服务器建立连接
    int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server));

    // 连接建立失败
    if (n < 0)
    {
        std::cerr<<"connect error"<<std::endl;
        exit(3);
    }

    while(true)
    {
        //1、输入消息
        std::cout<<"\nPlease Enter# ";

        std::string message;
        std::getline(std::cin,message);

        //2、发送消息
        ssize_t s=send(sockfd,message.c_str(),message.size(),0);

        if(s>0)
        {
            //3、接收应答
            char inbuffer[1024];
            ssize_t r=recv(sockfd,inbuffer,sizeof(inbuffer)-1,0);

            //接收成功
            if(r>0)
            {
                inbuffer[r]=0;
                std::cout<<inbuffer<<std::endl;
            }
            //接收失败
            else
            {
                break;
            }

        }
        else
        {
            break;
        }
        
    }

    shutdown(sockfd,SHUT_WR);

    return 0;
}